package me.xinping.record.controllers

import android.media.MediaMetadataRetriever
import android.net.Uri
import me.xinping.libs.base.BaseApp
import me.xinping.libs.recording.RecordFileUtils
import me.xinping.libs.recording.RecorderManager
import me.xinping.libs.recording.RecorderPlayer
import me.xinping.libs.utils.FAsyncTask
import me.xinping.libs.utils.FileUtils
import me.xinping.libs.utils.TimeUtils
import me.xinping.libs.utils.ToastHelper
import me.xinping.record.R
import me.xinping.record.extension.show
import me.xinping.record.ui.MainActivity
import me.xinping.record.ui.adapter.RecorderAdapter
import java.io.File

/**
 * MainActivity的控制器.
 * <p>
 * Date 2018/12/4
 * @author fanxinping_cd@keruyun.com
 */
class MainActivityController(private val activity: MainActivity) {
    private val recordManager: RecorderManager = RecorderManager.instance
    private val mmr = MediaMetadataRetriever()
    private val recorderListener = object : RecorderManager.OnRecordingListener {
        override fun onStart() {
            activity.isRecording = true
        }

        override fun onStop() {
            activity.isRecording = false
        }

        override fun onProgress(seconds: Int) {
            activity.updateRecordTime(seconds)
        }

    }

    private val playingListener = object : RecorderPlayer.OnPlayingListener {
        override fun onStart(filePath: String?) {
            activity.updateItemPlay(filePath, true)
        }

        override fun onStop(filePath: String?) {
            activity.updateItemPlay(filePath, false)
        }

        override fun onProgress(filePath: String?, seconds: Int) {
            activity.updateItemPlay(filePath, true, seconds)
        }

    }

    /**
     * 开始录音
     */
    fun startRecord() {
        recordManager.startRecording(RecordFileUtils.generateRecordFilePath(), recorderListener)
    }

    /**
     * 停止录音
     */
    fun stopRecord() {
        recordManager.stopRecording()
    }

    /**
     * 播放录音文件
     */
    fun playRecordFile(filePath: String) {
        if (filePath.isEmpty() || !File(filePath).exists()) {
            ToastHelper.show(activity.getString(R.string.app_aource_file_not_exist))
            return
        }
        RecorderPlayer.instance.playingListener = playingListener
        RecorderPlayer.instance.play(filePath)
    }

    fun stopPlay() {
        RecorderPlayer.instance.stop()
    }

    /**
     * 加载该app的录音文件列表
     */
    fun loadRecorderFileItems() {
        FAsyncTask(object : FAsyncTask.IFAsync<ArrayList<RecorderAdapter.RecorderItem>> {
            override fun execute(): ArrayList<RecorderAdapter.RecorderItem> {
                val recorderFiles = RecordFileUtils.loadRecorderFiles()
                val items = ArrayList<RecorderAdapter.RecorderItem>()
                (0 until recorderFiles.size).mapTo(items) {
                    val fileName = recorderFiles[it]
                    val file = File(FileUtils.RECORD_ROOT_PATH.plus(fileName))
                    val filePath = file.absolutePath
                    RecorderAdapter.RecorderItem(
                        fileName,
                        TimeUtils.seconds2Time(recordFileDuration(filePath)),
                        TimeUtils.getDate(TimeUtils.SDF_YMD_HM, file.lastModified()),
                        filePath
                    )
                }
                return items
            }

            override fun executeFinish(result: ArrayList<RecorderAdapter.RecorderItem>) {
                activity.updateItems(result)
            }
        }).execute()

    }

    private fun recordFileDuration(filePath: String): Int {
        if (filePath.isEmpty()) return 0
        val file = File(filePath)
        if (!file.exists() || file.length() == 0L) {
            return 0
        }
        mmr.setDataSource(BaseApp.instance, Uri.parse(filePath))
        val duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
        return duration.toInt() / 1_000
    }

    /**
     * 释放所有资源
     */
    fun releaseAll() {
        RecorderManager.instance.releaseRecoder()
    }
}